﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MosWar;
using StaticPlugin;
using System.Windows.Forms;

namespace MosWar
{
    class jTrainPet : AJob
    {
        class StatParser
        {
            public int statPrice = -1;
            public string name = "";
            public bool error = false;
            HtmlElement btnTrain;
            public StatParser(HtmlElement elemStat)
            {
                if (elemStat.GetAttribute("className") != "stat")
                {
                    error = true;
                    return;
                }
                name = WebParserEx.getTagByClassName(elemStat, "div", "label").OuterText;
                btnTrain = WebParserEx.getTagByClassName(elemStat, "button", "button");
                if (btnTrain == null)
                {
                    btnTrain = WebParserEx.getTagByClassName(elemStat, "button", "button disabled");
                    if (btnTrain == null)
                    {
                        error = true;
                        return;
                    }
                }
                if (!int.TryParse(WebParserEx.getTagByClassName(btnTrain, "span", "tugriki").OuterText.Replace(",", ""), out statPrice))
                {
                    error = true;
                    return;
                }
            }

            public void click()
            {
                btnTrain.InvokeMember("click");
            }
        }

        private string status = "";
        private bool available 
        {
            get
            {
                return Properties.Settings.Default.cbTrainPetActive;
            }
            set
            {
                Properties.Settings.Default.cbTrainPetActive = value;
                Properties.Settings.Default.Save();
            }
        }
        private jTrainPetSetup setup = new jTrainPetSetup();
        private int minMoneyToTrain 
        {
            get 
            {
                return (int)Properties.Settings.Default.numPetMinBablo;
            }
        }
        private DateTime activateTrainDate //= DateTime.Now;
        {
            get
            {
                DateTime dt = DateTime.Now;
                if (DateTime.TryParse(Properties.Settings.Default.dtProcessTimeTrainPet, out dt))
                {
                    return dt;
                }
                else
                {
                    Properties.Settings.Default.dtProcessTimeTrainPet = DateTime.Now.ToString();
                    Properties.Settings.Default.Save();
                    return DateTime.Now;
                }
            }
            set 
            {
                Properties.Settings.Default.dtProcessTimeTrainPet = value.ToString();
            }
        }
        private int minimalPrice
        {
            get
            {
                return Properties.Settings.Default.minimapPriceToTrainPet;
            }
            set
            {
                Properties.Settings.Default.minimapPriceToTrainPet = value;
                Properties.Settings.Default.Save();
            }
        }

        protected override string getName()
        {
            return "Тренировка питомца";
        }

        protected override string getStatus()
        {
            return status;
        }

        protected override bool getAvailable()
        {
            return  available;
        }

        protected override int getPriority()
        {
            return (int)Properties.Settings.Default.numPetPriority;
        }

        public override bool testRequirements(WebBrowser browser)
        {
            if (browser.Url != null && browser.Url.Segments.ToList().IndexOf("petarena/") >= 0) 
            {
                // проверим, не отдыхает ли питомец сейчас
                HtmlElement trainPanel = browser.Document.Body.GetElementsByTagName("span")["trainpanel"];
                //trainPanel = WebParserEx.getTagByCLassName(b.Document.Body, "table", "process");
                if (trainPanel != null && trainPanel.GetElementsByTagName("table").Count > 0)
                {
                    HtmlElement trainRestValue = trainPanel.GetElementsByTagName("span")["train"];
                    int timer = -1;
                    if (!int.TryParse(trainRestValue.GetAttribute("timer"), out timer))
                    {
                        //dropActions("!int.TryParse(trainRestValue.GetAttribute(\"timer\"), out strTimer)");
                        return activateTrainDate < DateTime.Now;
                    }
                    activateTrainDate = DateTime.Now.AddSeconds(TimeSpan.FromSeconds(timer).TotalSeconds);
                    status = "Следующая активация в " + activateTrainDate.ToShortTimeString();
                    
                }
            }
            if (activateTrainDate > DateTime.Now) 
            {
                status = "Следующая активация в " + activateTrainDate.ToShortTimeString();
                return false;
            }
            if (SkillsDetector.getMoney(browser) < minimalPrice + minMoneyToTrain) 
            {
                status = "Не хватает денег. надо мин. " + (minimalPrice + minMoneyToTrain).ToString();
                return false;
            }
            return true;
        }

        public override DialogResult showSetupDialog()
        {
            return setup.ShowDialog();
        }

        private void log(string s) 
        {
            Console.WriteLine("Critical error in jTrainPet: "+ s);
        }

        private void dropActions(string s)
        {
            log(s);
            actions.Clear();
            available = false;
        }

        public override void initActions()
        {
            actions.Clear();
            actions.Add(new Action("", GoToPetFactory));
            actions.Add(new Action("", ChoicePet));
            actions.Add(new Action("", AnalyzePetTrain));
        }

        public void GoToPetFactory(WebBrowser b) 
        {
            // пока выбираем первого питомца в списке
            b.Navigate("www.moswar.ru/petarena");
        }

        public void ChoicePet(WebBrowser b) 
        {
            HtmlElement PetsCollection = WebParserEx.getTagByClassName(b.Document.Body, "div", "object-thumbs");
            if (PetsCollection == null)
            {
                dropActions("PetsCollection == null");
                return;
            }
            // пока выбираем первого питомца в списке
            HtmlElement PetToTrain = WebParserEx.getTagByClassName(PetsCollection, "div", "action");
            if (PetToTrain == null) 
            {
                dropActions("PetToTrain == null");
                return;
            }
            PetToTrain.InvokeMember("click");
        }

        public void AnalyzePetTrain(WebBrowser b) 
        {
            // проверим, не отдыхает ли питомец сейчас
            HtmlElement trainPanel = b.Document.Body.GetElementsByTagName("span")["trainpanel"];
            //trainPanel = WebParserEx.getTagByCLassName(b.Document.Body, "table", "process");
            if (trainPanel.GetElementsByTagName("table").Count > 0)
            {
                HtmlElement trainRestValue = trainPanel.GetElementsByTagName("span")["train"];
                int timer = -1;
                if (!int.TryParse(trainRestValue.GetAttribute("timer"), out timer)) 
                {
                    dropActions("!int.TryParse(trainRestValue.GetAttribute(\"timer\"), out strTimer)");
                    return;
                }
                activateTrainDate = DateTime.Now.AddSeconds(TimeSpan.FromSeconds(timer).TotalSeconds);
                status = "Следующая активация в " + activateTrainDate.ToShortTimeString();
                return;
            }
            
            HtmlElement StatsCollection = WebParserEx.getTagByClassName(b.Document.Body, "ul", "stats");
            if (StatsCollection == null)
            {
                dropActions("StatsCollection == null");
                return;
            }
            int stats = 0;
            StatParser statToProcess = null;

            foreach (HtmlElement elemStat in StatsCollection.GetElementsByTagName("li")) 
            {
                StatParser stat = new StatParser(elemStat);
                if (stat.error) continue;
                stats++;
                {
                    if (statToProcess == null || statToProcess.statPrice > stat.statPrice)
                        statToProcess = stat;
                }
            }
            Console.WriteLine("Найдено " + stats.ToString() + " статов для прокачки");
            if (statToProcess != null && SkillsDetector.getMoney(b) > statToProcess.statPrice + minMoneyToTrain) 
            {
                statToProcess.click();
                log("Начали прокачку стата: " + statToProcess.name);
                return;
            }
            if (statToProcess != null) // денег нехватило.. 
            {
                minimalPrice = statToProcess.statPrice;
                status = "Не хватает денег. Надо мин. "+minimalPrice.ToString();
            }
        }
    }
}
